package cn.piesat.util;

import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Objects;


public class AddressUtil {
    private static final Logger log = LoggerFactory.getLogger(AddressUtil.class);

    public static String getCityInfo(String ip)
    {
        DbSearcher searcher = null;
        try
        {
            String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
            File file = new File(dbPath);
            if (!file.exists())
            {
                String tmpDir = getPath();
                dbPath = File.separator+ tmpDir + "ip.db";
                file = new File(dbPath);
                FileUtils.copyInputStreamToFile((InputStream) Objects.requireNonNull(AddressUtil.class.getResourceAsStream("/ip2region/ip2region.db")), file);
            }
            DbConfig config = new DbConfig();
            searcher = new DbSearcher(config, file.getPath());
            Method method = null;
            method = searcher.getClass().getMethod("btreeSearch", new Class[] { String.class });
            DataBlock dataBlock = null;
            if (!Util.isIpAddress(ip)) {
                log.error("Error: Invalid ip address");
            }
            dataBlock = (DataBlock)method.invoke(searcher, new Object[] { ip });
            if(dataBlock !=null){
                return dataBlock.getRegion();
            }
            return "";
        }
        catch (Exception e)
        {
            log.error("获取地址信息异常", e);
        }
        finally
        {
            if (searcher != null) {
                try
                {
                    searcher.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    private static String getPath(){
        // 获取项目路径（兼容war服务和jar服务）
        String rootPath = AddressUtil.class.getResource("/").getPath();
        String[] splits = rootPath.split("/");
        int breakI = 0;
        boolean isJarService = false;// 项目是否是打成jar包发布
        for (int i = 0; i < splits.length; i++) {
            if (splits[i].contains(".jar")){
                breakI = i;
                isJarService = true;
                break;
            }
        }
        String finalRootPath = "";
        if (isJarService){
            // 打成jar包后，获取的路径中会以file:XXX/XXX开头，所以去除切割后的第一个路径，i从1开始遍历
            for (int i = 1; i < breakI; i++) {
                finalRootPath += splits[i] + "/";
            }
        } else {
            finalRootPath = rootPath;
        }
        return finalRootPath;
    }

}
